const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const OrderItem = sequelize.define('OrderItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    order_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '订单ID'
    },
    product_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '产品ID'
    },
    product_name: {
      type: DataTypes.STRING(200),
      allowNull: false,
      comment: '产品名称快照'
    },
    product_sku: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '产品编码快照'
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '数量'
    },
    unit_price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '单价'
    },
    discount_rate: {
      type: DataTypes.DECIMAL(5, 4),
      defaultValue: 0,
      comment: '折扣率'
    },
    discount_amount: {
      type: DataTypes.DECIMAL(10, 2),
      defaultValue: 0,
      comment: '折扣金额'
    },
    line_total: {
      type: DataTypes.DECIMAL(12, 2),
      allowNull: false,
      comment: '行总金额'
    },
    notes: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '备注'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  }, {
    tableName: 'order_items',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    comment: '订单项表',
    indexes: [
      {
        fields: ['order_id']
      },
      {
        fields: ['product_id']
      }
    ]
  })

  return OrderItem
}